//
//  DataFetchController.m
//  WeatherDesktop
//
//  Created by Justin Dell on 10/27/08.
//  Copyright 2008 . All rights reserved.
//

#import "DataFetchController.h"
#import "YahooWeatherData.h"


@implementation DataFetchController

/**
 *  Delegate method called when the window is awoken
 *  Runs the loop that refreshes the desktop
 */
-(void)awakeFromNib {
    double refresh;
    NSString *zip;
    [zipCode bind:@"value"
        toObject:[NSUserDefaultsController sharedUserDefaultsController]
        withKeyPath:@"values.zipCode"
        options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
        forKey:@"NSContinuouslyUpdatesValue"]];
    [refreshRate bind:@"value"
        toObject:[NSUserDefaultsController sharedUserDefaultsController]
        withKeyPath:@"values.refreshRate"
        options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
        forKey:@"NSContinuouslyUpdatesValue"]];
    refresh = [refreshRate doubleValue];
    zip = [zipCode stringValue];
    if (refresh == 0.0) {
        refresh = 10;
        zip = @"61820";
        [prefPanel makeKeyAndOrderFront:nil];
    }
    wpModifier = [[WallpaperModifier alloc] 
        initWithZip:zip
        andRefresh:(refresh * 60)];
}

/**
 *  Called when user presses refresh, cancelling old wallpaper loop and restarting it
 *  in order to automatically update the wallpaper
 */
-(IBAction)refreshButton:(id)sender {
    [wpModifier setWallpaper:nil];
}

/**
 * User hit the apply button to update the zip code and refresh rate
 */
-(IBAction)apply:(id)sender {
    double ref = [refreshRate doubleValue];
    if (ref <= 0) {
        NSString *theAlertMessage = 
            @"Please enter a refresh rate above zero";
        NSRunAlertPanel( @"Error", theAlertMessage, @"OK", nil, nil );    
    }

    [[[NSUserDefaultsController sharedUserDefaultsController] values] 
        setValue:[zipCode stringValue]
        forKey:@"zipCode"];
    [[[NSUserDefaultsController sharedUserDefaultsController] values] 
        setValue:[refreshRate stringValue]
        forKey:@"refreshRate"];
    [wpModifier setZipCode:[zipCode stringValue]];
    [wpModifier setRefreshRate:(ref * 60)];
    [prefPanel close];
}

/**
 * Hides the window when the user closes it
 */
-(BOOL)windowShouldClose:(id)window {
    [weatherWindow orderOut:nil];
    return NO;
}

/**
 * Opens window when dock is clicked
 */
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication
                    hasVisibleWindows:(BOOL)flag {
    if( !flag ) {
        [weatherWindow makeKeyAndOrderFront:self];
    }
    return YES;
} 

@end
